import { Injectable } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Company } from "src/modules/company/company.entity";
import { CompanyService } from "src/modules/company/company.service";
import { CreateQualityDto } from "src/modules/quality/dto/create-quality.dto";
import { dateNewFirst } from "src/utils/util";
import { Repository } from "typeorm";
import { Quality } from "./quality.entity";

@Injectable()
export class QualityService {
  constructor(
    @InjectRepository(Quality)
    private readonly qualityRepository: Repository<Quality>,
    private readonly companyService: CompanyService
  ) {}
  async findAll(): Promise<Quality[]> {
    return (await this.qualityRepository.find()).sort(dateNewFirst);
  }
  async findByCompany(companyId: string): Promise<Quality[]> {
    const company = await this.companyService.find(companyId);
    return (
      await this.qualityRepository.find({
        company,
      })
    ).sort(dateNewFirst);
  }
  find(id: string): Promise<Quality> {
    return this.qualityRepository.findOneOrFail(id, { relations: ["company"] });
  }
  findOneWithCompany(id: string): Promise<Quality> {
    return this.find(id);
  }
  async create(
    createQualityDto: CreateQualityDto,
    company: string | Company
  ): Promise<Quality> {
    const quality = new Quality();
    company =
      company instanceof Company
        ? company
        : await this.companyService.find(company);
    Object.assign(quality, createQualityDto, { date: new Date() }, { company });
    quality.date.setUTCMilliseconds(0);
    return this.qualityRepository.save(quality);
  }
  async remove(quality: string | Quality): Promise<Quality> {
    const id = quality instanceof Quality ? quality.id : quality;
    const qualityToRemove = await this.find(id);
    return await this.qualityRepository.remove(qualityToRemove);
  }
}
